package com.only4play.authcenter.infrastructure.security;

import com.only4play.authcenter.infrastructure.security.config.LoginProperties;
import com.only4play.authcenter.infrastructure.security.entrypoint.CustomAuthenticationEntryPoint;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;

import static com.only4play.authcenter.infrastructure.security.configurers.admin.PassLoginConfigurer.passLogin;

/**
 * @author hinzzz www.hinzzz.cn 157957329@qq.com
 * 2024-03-05
 */
@Configuration
@RequiredArgsConstructor
@EnableWebSecurity
public class PlatformAuthenticationConfiguration {
    private final LoginProperties loginProperties;

    @Bean
    @Order(1)
    public SecurityFilterChain authorizationSecurityFilterChain(HttpSecurity http) throws Exception {
        http.apply(passLogin());
        http.authorizeHttpRequests(authorize -> {
                    authorize.antMatchers(loginProperties.getPassAuthUrl(), loginProperties.getSmsAuthUrl()).permitAll();
                    authorize.antMatchers("/test/**").permitAll();
                    authorize.anyRequest().authenticated();
                })
                .exceptionHandling(exceptionHandling -> {
                    exceptionHandling.authenticationEntryPoint(new CustomAuthenticationEntryPoint());
                })
                .sessionManagement(sm -> {
                    sm.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
                })
                .csrf(AbstractHttpConfigurer::disable);
        return http.build();
    }
}
